package com.senriot.quickup.service.mapper

import com.senriot.cloud.common.IEntityMapper
import com.senriot.quickup.domain.Product
import com.senriot.quickup.domain.QDevice
import com.senriot.quickup.repository.DeviceRepository
import com.senriot.quickup.service.dto.ProductDTO
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.Mappings
import org.mapstruct.NullValuePropertyMappingStrategy
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier

@Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
abstract class ProductMapper : IEntityMapper<ProductDTO, Product>
{


    @Qualifier("deviceRepository") @Autowired private lateinit var deviceRepository: DeviceRepository

    fun fromId(id: Int?) = id?.let { Product().apply { this.id = it } }


    @Mappings(
        Mapping(target = "deviceCount", source = "id", qualifiedByName = ["deviceCount"])
    )
    abstract override fun toDto(entity: Product): ProductDTO

    fun deviceCount(id: Int): Long
    {
        return deviceRepository.count(QDevice.device.product.id.eq(id))
    }
}
